﻿exports.save_loc = function (req, res) {
    var RESULT_SUCESS = 0;
    var RESULT_ERROR = -1;
    var fs = require("fs");
    var pconfig = require("../common/config").config;
    var DateUtils = require("../common/dateUtils").DateUtils;
    var now = new Date();
    var d = DateUtils.dateToString(now);
    var suffix = DateUtils.dateToString(now, "yyyy-MM-dd");
    var fullPath = pconfig.filePathPrefix + pconfig.gpsFileName + "." + suffix;
    if (req.method == "POST") {
        var datas = req.body;
        var isSuccess = true;
        for (var i = 0; i < datas.length; i++) {            
            var DBUtils = null;
            
            var dbType = pconfig.useDB;
            var url;
            if (dbType == "mongo") {
                url = pconfig.dbUrl;
                DBUtils= require("../common/MongoDBUtils").DBUtils;
            } else if (dbType == "mysql") {
                url = pconfig.mysqlConfig;
                DBUtils = require("../common/MysqlDBUtils").DBUtils;
            }

            DBUtils.getConnection(url, datas[i]).then(function (rdb) {
                var db = rdb.result;
                DBUtils.insert(db, "gps", rdb.object).then(function (r) {
                    db.commit(function (err) {
                        if (err) {
                            db.rollback(function () {
                                console.log(err);
                                DBUtils.close(db);
                            });
                        } else {
                            DBUtils.close(db);
                        }
                    });
                }).catch(function (err) {
                    console.log(err);
                    db.commit(function (err) {
                        if (err) {
                            db.rollback(function () {
                                console.log(err);
                                DBUtils.close(db);
                            });
                        } else {
                            DBUtils.close(db);
                        }
                    });
                })                ;
                
                
            }).catch(function (err) { 
                console.log(err);
            });
            
            fs.appendFile(fullPath, '[' + d + ']' + JSON.stringify(datas[i]) + '\n', function (err) {
                if (err) {
                    isSuccess = false;
                    console.log(err);
                }
            });
        }        
    }
    var result = {};
    if (isSuccess) {
        result = { code: RESULT_SUCESS, interval: 10000, message: null };
    } else {
        result = { code: RESULT_ERROR, interval: 10000, message: "save file error." };
    }
    res.send(JSON.stringify(result));
};